package cn.edu.zjut.medlinebackend.controller;


import cn.edu.zjut.medlinebackend.model.User;
import cn.edu.zjut.medlinebackend.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @RequestMapping("/loginService")
    public String checkLoginValidity(@ModelAttribute("user") User user, HttpServletResponse response) {
        if (userService.checkLoginValidity(user, response).equals("failed")) {

            return "user/loginFailed";
        } else if (userService.checkLoginValidity(user, response).equals("user")) {

            return "user/home";
        } else {

            return "user/adminHome";
        }
    }

    @GetMapping("/adminhome")
    public String adminHome(HttpServletRequest request) {
         return "user/adminHome";
    }

    @GetMapping("/setting")
    public String redirectToAppropriateSettings(HttpServletRequest request) {
        if (userService.checkIsAdmin(request)) return "user/adminSetting";
        else return "user/userSetting";
    }

    @RequestMapping("creatUser")
    public String checkUserCreated(User user) {
        if (userService.creatUser(user)) return "user/success";
        else return "user/failed";
    }

    @GetMapping("/searchUser")
    public String getRecords(Model model) {
        List<User> users = userService.searchAllUser();
        model.addAttribute("users", users);
        return "user/userList";
    }

    @GetMapping("/deleteUser/{username}")
    public String deleteUser(@PathVariable String username) {
        if (userService.deleteUserInfo(username)) return "user/success";
        else return "user/failed";
    }

    @RequestMapping("/submitAndRegister")
    public String checkUserRegister(@ModelAttribute User user) {
        user.setRole("user");
        if (userService.creatUser(user)) return "user/login";
        else return "user/failed";
    }

    @GetMapping("/updateUser/{username}")
    public String updateUser(@PathVariable("username") String username, Model model) {
        User user = userService.searchUser(username);
        model.addAttribute("user", user);
        return "user/updateUserInfo";
    }

    @RequestMapping("submitAndUpdateUser")
    public String checkUserUpdate(User user) {
        if (userService.updateUser(user)) return "user/success";
        else return "user/failed";
    }

}
